<template>
   <div class="login_main_container">
      <!-- 学校logo -->
      <el-image :src="require('@/assets/images/school_logo.png')" style="
            position: absolute;
            left: 15px;
            top: 15px;
            width: 350px;
            height: 75px;
            opacity: 2 !important;
            object-fit: fill;
         "></el-image>

      <!-- 登录界面 -->
      <div>
         <el-dialog class="login_form" v-model="loginDialogShow" :close-on-click-modal="false"
            :close-on-press-escape="false" :showClose="false" width="760px" style="margin-top: 230px; position: relative">
            <template #header>
               <span
                  style="position: absolute; top: -65px; left: 240px; font-family: Source Han Sans; font-weight: 550; font-size: 36px; color: #fff;">
                  专业招生质量分析
               </span>
            </template>

            <div style="height: 100%; width: 100%; opacity: 1 !important">
               <el-row type="flex" justify="center" style="margin-top: -15px">
                  <el-col :span="6">
                     <el-image :src="require('@/assets/images/computing_logo.png')" style="
                           width: 160px;
                           height: 160px;
                           margin-top: 40px;
                           opacity: 1 !important;
                           object-fit: fill;
                        "></el-image>
                  </el-col>

                  <el-col :span="1">
                     <el-divider direction="vertical" class="el-divider--vertical"></el-divider>
                  </el-col>

                  <el-col :span="17">
                     <div>
                        <span style="font-weight: bold; font-size: 30px">用户登录</span>
                        <el-form style="margin-top: 40px" :model="loginForm" :rules="loginInputRules" ref="loginFormDom">
                           <el-form-item label="账号" label-width="100" prop="username">
                              <el-input style="width: 380px" v-model="loginForm.username"
                                 placeholder="请输入学号/学工号："></el-input>
                           </el-form-item>
                           <el-form-item label="密码" label-width="100" prop="password" style="margin-top: 20px">
                              <el-input style="width: 380px" v-model="loginForm.password" show-password
                                 @keydown.enter="login()" placeholder="请输入密码："></el-input>
                           </el-form-item>
                        </el-form>
                     </div>
                     <div style="
                           margin-top: -2px;
                           margin-right: -400px;
                           font-size: 10px;
                           color: #aaaaaa;
                        ">
                        <span class="forget_password" @click="forgetPasswordDialogShow = true">忘记密码</span>
                     </div>
                  </el-col>
               </el-row>
            </div>

            <template #footer>
               <span>
                  <el-button @click="registerDialogShow = true">注 册</el-button>
                  <el-button type="primary" @click="login()">登 录</el-button>
               </span>
            </template>
         </el-dialog>
      </div>

      <!-- 用户注册 -->
      <div>
         <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" v-model="registerDialogShow"
            width="600px">
            <template #header>
               <span style="font-size: 20px; font-weight: 600">用户注册</span>
            </template>

            <div>
               <el-form ref="registerFormDom" :model="registerForm" :rules="registerFormRules">
                  <el-form-item label="真实姓名" label-width="100" prop="name">
                     <el-input v-model="registerForm.name" style="width: 380px" placeholder="请输入真实姓名："></el-input>
                  </el-form-item>
                  <el-form-item label="登录账号" label-width="100" prop="stuId">
                     <el-input v-model="registerForm.stuId" style="width: 380px" placeholder="请输入学号/学工号："></el-input>
                  </el-form-item>
                  <el-form-item label="用户密码" label-width="100" prop="password">
                     <el-input v-model="registerForm.password" style="width: 380px" show-password
                        placeholder="请输入密码："></el-input>
                  </el-form-item>
                  <el-form-item label="确认密码" label-width="100" prop="repassword">
                     <el-input v-model="registerForm.repassword" style="width: 380px" show-password
                        placeholder="请再次输入密码："></el-input>
                  </el-form-item>
                  <el-form-item label="手机号码" label-width="100" prop="telephone">
                     <el-input v-model="registerForm.telephone" style="width: 380px" placeholder="请输入手机号："></el-input>
                  </el-form-item>
                  <el-form-item label="学校邮箱" label-width="100" prop="email" style="position: relative">
                     <el-input v-model="registerForm.email" style="width: 380px" placeholder="请输入学校邮箱："></el-input>
                     <el-button v-show="!sendEmailWaitButtonShow" @click="sendVerificationCode(0)" style="
                           position: absolute;
                           right: 81px;
                           background-color: #a1d0f0;
                           width: 18%;
                           height: 30px;
                           font-size: 12px;
                        ">发送验证码</el-button>
                     <el-button v-show="sendEmailWaitButtonShow" disabled style="
                           position: absolute;
                           right: 81px;
                           background-color: #a1d0f0;
                           width: 18%;
                           height: 30px;
                           font-size: 14px;
                           color: #7280f7;
                        ">
                        {{ waitTime }}</el-button>
                  </el-form-item>

                  <el-form-item label="验证码" label-width="100" prop="authCode">
                     <el-input v-model="registerForm.authCode" style="width: 380px" placeholder="请输入验证码："></el-input>
                  </el-form-item>
               </el-form>
            </div>

            <template #footer>
               <el-button @click="registerDialogShow = false">取 消</el-button>
               <el-button type="primary" @click="register()">注 册</el-button>
            </template>
         </el-dialog>
      </div>

      <!-- 忘记密码 -->
      <div>
         <el-dialog style="margin-top: 218px" :close-on-click-modal="false" :close-on-press-escape="false"
            v-model="forgetPasswordDialogShow" width="600px">
            <template #header>
               <span style="font-size: 20px; font-weight: 600">找回密码</span>
            </template>

            <div>
               <el-form ref="forgetPasswordFormDom" :model="forgetPasswordForm" :rules="forgetPasswordFormRules">
                  <el-form-item label="学校邮箱" label-width="100" prop="email" style="position: relative">
                     <el-input v-model="forgetPasswordForm.email" style="width: 380px" placeholder="请输入学校邮箱："></el-input>
                     <el-button v-show="!sendEmailWaitButtonShow" @click="sendVerificationCode(1)" style="
                           position: absolute;
                           right: 81px;
                           background-color: #a1d0f0;
                           width: 18%;
                           height: 30px;
                           font-size: 12px;
                        ">发送验证码</el-button>
                     <el-button v-show="sendEmailWaitButtonShow" disabled style="
                           position: absolute;
                           right: 81px;
                           background-color: #a1d0f0;
                           width: 18%;
                           height: 30px;
                           font-size: 14px;
                           color: #7280f7;
                        ">
                        {{ waitTime }}</el-button>
                  </el-form-item>
                  <el-form-item label="验证码" label-width="100" prop="authCode">
                     <el-input v-model="forgetPasswordForm.authCode" style="width: 380px" placeholder="请输入验证码："></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" label-width="100" prop="password">
                     <el-input v-model="forgetPasswordForm.password" style="width: 380px" show-password
                        placeholder="请输入新密码："></el-input>
                  </el-form-item>
                  <el-form-item label="确认密码" label-width="100" prop="repassword">
                     <el-input v-model="forgetPasswordForm.repassword" style="width: 380px" show-password
                        placeholder="请再次输入密码："></el-input>
                  </el-form-item>
               </el-form>
            </div>

            <template #footer>
               <el-button @click="forgetPasswordDialogShow = false">取 消</el-button>
               <el-button type="primary" @click="resetPassword()">重 置</el-button>
            </template>
         </el-dialog>
      </div>
   </div>
</template>

<script>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import $axios from "@/axios";
import { ElMessage } from "element-plus";

export default {
   name: "LoginPage",
   setup() {
      const router = useRouter();

      // 登录、注册、忘记密码窗口是否显示
      const loginDialogShow = ref(true);
      let registerDialogShow = ref(false);
      let forgetPasswordDialogShow = ref(false);

      // 发送验证码后等待按钮是否显示
      let sendEmailWaitButtonShow = ref(false);

      let waitTime = ref(60);

      // 登录表单输入规则
      const loginInputRules = {
         username: [
            { required: true, message: "请输入登录账号", trigger: "blur" },
            {
               min: 1,
               max: 15,
               message: "长度在 1 到 15 个字符以内",
               trigger: "blur",
            },
         ],
         password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      };

      // 注册表单输入规则
      const registerFormRules = {
         name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
         stuId: [
            { required: true, message: "请输入学号/学工号", trigger: "blur" },
            {
               min: 1,
               max: 10,
               message: "长度在 1 到 15 个字符",
               trigger: "blur",
            },
         ],
         password: [{ required: true, message: "请输入密码", trigger: "blur" }],
         repassword: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  if (value !== registerForm.password) {
                     callback(new Error("两次输入密码不一致!"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
         telephone: [
            { required: true, message: "请输入联系电话", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  const reg = /^[1][3-9][0-9]{9}$/;
                  if (!reg.test(value) && value != "") {
                     callback(new Error("请输入正确的电话号码"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
         email: [
            { required: true, message: "请输入学校邮箱", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  const reg =
                     /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
                  if (!reg.test(value) && value != "") {
                     callback(new Error("请输入正确的学校邮箱"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
         authCode: [
            { required: true, message: "请输入验证码", trigger: "blur" },
            {
               min: 6,
               max: 6,
               message: "验证码格式不正确",
               trigger: "blur",
            },
         ],
      };

      // 找回密码表单输入规则
      const forgetPasswordFormRules = {
         password: [{ required: true, message: "请输入密码", trigger: "blur" }],
         repassword: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  if (value !== forgetPasswordForm.password) {
                     callback(new Error("两次输入密码不一致!"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
         email: [
            { required: true, message: "请输入学校邮箱", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  const reg =
                     /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
                  if (!reg.test(value) && value != "") {
                     callback(new Error("请输入正确的学校邮箱"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
         authCode: [
            { required: true, message: "请输入验证码", trigger: "blur" },
            {
               min: 6,
               max: 6,
               message: "验证码格式不正确",
               trigger: "blur",
            },
         ],
      };

      // 登录、注册、忘记密码表单dom
      const loginFormDom = ref(null);
      const registerFormDom = ref(null);
      const forgetPasswordFormDom = ref(null);

      // 登录表单
      let loginForm = reactive({
         username: "",
         password: "",
      });

      // 注册表单
      let registerForm = reactive({
         name: "",
         stuId: "",
         email: "",
         password: "",
         repassword: "",
         telephone: "",
         authCode: "",
      });

      // 找回密码表单
      let forgetPasswordForm = reactive({
         email: "",
         authCode: "",
         password: "",
         repassword: "",
      });

      // 登录
      function login() {
         loginFormDom.value.validate((valid) => {
            if (valid) {
               $axios.post("/user/login", loginForm).then((resp) => {
                  localStorage.setItem("token", resp.data.data);

                  ElMessage({
                     type: "success",
                     message: "登录成功，欢迎回来",
                     duration: 2000,
                  });

                  router.replace({
                     path: "/",
                  });
               });
            } else {
               ElMessage({
                  type: "error",
                  message: "请正确填写登录信息",
                  duration: 1500,
               });
            }
         });
      }

      // 注册
      function register() {
         registerFormDom.value.validate((valid) => {
            if (valid) {
               $axios.post("/user/register", registerForm).then((resp) => {
                  // 关闭注册框
                  registerDialogShow.value = false;

                  // 清空注册表单的值
                  Object.keys(registerForm).forEach(
                     (key) => (registerForm[key] = "")
                  );

                  ElMessage({
                     type: "success",
                     message: "注册成功",
                     duration: 2000,
                  });
               });
            } else {
               ElMessage({
                  type: "error",
                  message: "请正确填写注册信息",
                  duration: 1500,
               });
            }
         });
      }

      // 发送验证码
      function sendVerificationCode(dom) {
         let formDom =
            dom === 0 ? registerFormDom.value : forgetPasswordFormDom.value;
         let form = dom === 0 ? registerForm : forgetPasswordForm;

         formDom.validateField("email", (valid) => {
            if (valid) {

               sendEmailWaitButtonShow.value = true;
               waitTime.value = 60;

               setInterval(() => {
                  if (waitTime.value > 0) {
                     waitTime.value--;
                  } else {
                     sendEmailWaitButtonShow.value = false;
                  }
               }, 1000);

               $axios.get("/user/getAuthCode/" + form.email).then((resp) => {
                  ElMessage({
                     type: "success",
                     message: "验证码发送成功，请到邮箱查看",
                     duration: 2000,
                  });
               });
            } else {
               ElMessage({
                  type: "error",
                  message: "请输入正确的邮箱",
                  duration: 1500,
               });
            }
         });
      }

      // 重置密码
      function resetPassword() {
         forgetPasswordFormDom.value.validate((valid) => {
            if (valid) {
               $axios
                  .put("/user/resetPassword", forgetPasswordForm)
                  .then((resp) => {
                     forgetPasswordDialogShow.value = false;

                     ElMessage({
                        type: "success",
                        message: "重置密码成功",
                        duration: 2000,
                     });
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请正确填写信息",
                  duration: 1500,
               });
            }
         });
      }

      return {
         loginDialogShow,
         loginForm,
         loginInputRules,
         loginFormDom,
         login,
         registerDialogShow,
         registerFormRules,
         registerFormDom,
         registerForm,
         register,
         sendEmailWaitButtonShow,
         waitTime,
         sendVerificationCode,
         forgetPasswordDialogShow,
         forgetPasswordFormRules,
         forgetPasswordForm,
         forgetPasswordFormDom,
         resetPassword,
      };
   },
};
</script>

<style scoped>
.login_main_container {
   width: 100%;
   height: 100%;
   background: url("@/assets/images/login_bg.png") no-repeat;
   background-size: cover;
}

.el-divider--vertical {
   display: inline-block;
   width: 1px;
   height: 16em;
   margin: 0 8px;
   vertical-align: middle;
   position: relative;
}

.forget_password {
   cursor: pointer;
}

.forget_password:hover {
   color: #214094;
}
</style>